import 'package:dio/dio.dart';
import 'package:dio/io.dart';
import 'dart:io';

class DioClient {
  static Dio? _dio;

  /// 获取配置好的 Dio 客户端
  /// allowBadCertificates: 是否允许不受信任的证书（用于 IP 地址访问）
  ///
  /// 注意：使用域名访问时，默认不需要忽略证书
  static Dio getDio({bool allowBadCertificates = false}) {
    if (_dio != null) {
      return _dio!;
    }

    print('🔧 初始化 Dio 客户端 (allowBadCertificates: $allowBadCertificates)');

    _dio = Dio(BaseOptions(
      connectTimeout: const Duration(seconds: 30),
      receiveTimeout: const Duration(seconds: 30),
      sendTimeout: const Duration(seconds: 30),
      followRedirects: true,  // 允许自动重定向
      maxRedirects: 5,
      headers: {
        'Connection': 'close',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
        'Accept': 'application/json, text/plain, */*',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
        'Accept-Encoding': 'gzip, deflate, br',
        'Cache-Control': 'no-cache',
        'Pragma': 'no-cache',
      },
    ));

    // 默认启用证书忽略（用于 IP 地址 HTTPS 访问）
    if (allowBadCertificates) {
      print('🔓 启用证书忽略模式');
      _dio!.httpClientAdapter = IOHttpClientAdapter(
        createHttpClient: () {
          final client = HttpClient();
          client.badCertificateCallback = (X509Certificate cert, String host, int port) {
            print('⚠️ 接受来自 $host:$port 的不受信任证书');
            return true;
          };
          return client;
        },
      );
    }

    // 添加请求和响应拦截器，用于调试
    _dio!.interceptors.add(
      InterceptorsWrapper(
        onRequest: (options, handler) {
          print('🌐 请求: ${options.method} ${options.uri}');
          handler.next(options);
        },
        onResponse: (response, handler) {
          handler.next(response);
        },
        onError: (DioException error, handler) {
          if (error.response != null) {
            print('❌ 状态码: ${error.response?.statusCode}');
            print('❌ 响应数据: ${error.response?.data}');
          }
          handler.next(error);
        },
      ),
    );

    return _dio!;
  }

  /// 重置 Dio 实例（用于重新配置）
  static void resetDio() {
    print('🔄 重置 Dio 客户端');
    _dio = null;
  }
}
